package com.itheima.userdetailservice;

import com.itheima.health.pojo.Permission;
import com.itheima.health.service.UserService;
import com.itheima.health.vo.RoleVO;
import com.itheima.health.vo.UserVO;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class MyUserDetailsService implements UserDetailsService {

    @Reference
    private UserService userService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //  多表查询   根据用户账号 查询 用户  账号  密码  用户所有角色关键字以及对于权限关键字
        //    UserVO  RoleVO    Permission
         UserVO userVO = userService.findUserInfoByUsername(username);
         if(userVO==null){
             return  null;
         }
         //  集合存放当前用户所有的 角色和权限关键字
        List<GrantedAuthority> authorities = new ArrayList<>();
        Set<RoleVO> roles = userVO.getRoles();
        for (RoleVO role : roles) {
              authorities.add(new SimpleGrantedAuthority(role.getKeyword()));
              //   角色对的的权限关键添加集合中
            Set<Permission> permissionSet = role.getPermissionSet();
            for (Permission permission : permissionSet) {
                authorities.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        User user = new User(userVO.getUsername(),userVO.getPassword(),authorities);
        return user;
    }
}
